package com.liu.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.liu.entity.Appraise;
import com.liu.entity.Physician;
import com.liu.entity.User;
import com.liu.service.AppraiseService;
import com.liu.service.PhysicianService;
import com.liu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.krb5.internal.HostAddress;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Appraise)表控制层
 *
 * @author makejava
 * @since 2023-02-09 12:34:32
 */
@RestController
@RequestMapping("/appraise")
@CrossOrigin
@Slf4j
public class AppraiseController {
    /**
     * 评论对象
     */
    private AppraiseService appraiseService;
    @Autowired
    @Qualifier("appraiseServiceImpl")
    public void setService(AppraiseService appraiseService){
        this.appraiseService = appraiseService;
    }

    /**
     * 医师对象
     */
    private PhysicianService physicianService;
    @Autowired
    @Qualifier("physicianServiceImpl")
    public void setPhysicianService(PhysicianService physicianService){
        this.physicianService = physicianService;
    }

    /**
     * 用户对象
     */
    private UserService userService;
    @Autowired
    @Qualifier("UserServiceImpl")
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize
    ){
        pageNum = (pageNum - 1) * pageSize;
        List<Appraise> data = appraiseService.queryAllByLimit(pageNum, pageSize);
        Long total = appraiseService.count();
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 个人评论
     *
     * @return 查询结果
     */
    @GetMapping("/userAppraise")
    public Map<String, Object> userAppraise(@RequestParam Integer pageNum,
                                            @RequestParam Integer pageSize,
                                            @RequestParam(defaultValue = "") Integer id
    ){
        pageNum = (pageNum - 1) * pageSize;
        List<Appraise> data = appraiseService.userAppraise(pageNum, pageSize, id);
        Long total = appraiseService.userCount(id);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 医生评论
     *
     * @return 查询结果
     */
    @PostMapping("/phyAppraise")
    public Map<String, Object> phyAppraise(Integer id){
        log.info("id是{}",id);
        List<Appraise> data = appraiseService.findAppraiseByPhy(id);
        Long total = appraiseService.phyCount(id);
        log.info("评论是{}",data);
        log.info("数量是{}",total);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 医院评论
     * @param id
     * @return
     */
    @PostMapping("/HosAppraise")
    public Map<String, Object> HosAppraise(Integer id){
        List<Appraise> data = appraiseService.findAppraiseByHos(id);
        Long total = appraiseService.hosCount(id);
        /*log.info("评论是{}",data);
        log.info("数量是{}",total);*/
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }


    /**
     * 计算评分
     * @param phyId
     * @return
     */
    public void phyScore(Integer phyId){
        List<Appraise> appraise = appraiseService.findAppraiseByPhy(phyId);
        double score;
        if (appraise == null) score =  0.0;
        else {
            Double scores = 0.0;
            int n = appraise.size();
            for (Appraise value : appraise) {
                scores += value.getScore();
            }
            score = (Math.round(scores*100/n)/100.0);
        }
        Physician physician = physicianService.queryById(phyId);
        physician.setScore(score);
        physicianService.update(physician);
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/list")
    public List<Appraise> findAll(){
        return this.appraiseService.findAll();
    }

    /**
     * 查询全部医师
     * @return
     */
    @GetMapping("/findPhy")
    public List<Physician> findPhy() {
        return physicianService.findAll();
    }

    /**
     * 查询全部用户
     * @return
     */
    @GetMapping("/findUser")
    public List<User> findUser() {
        return userService.findAllUser();
    }

    /**
     * 添加或更新
     *
     * @param appraise
     */
    @PostMapping("/edit")
    public int insert(@RequestBody Appraise appraise) {
        log.info("当前保存或修改的信息:{}", appraise.toString());
        //根据传递过来的参数studentId是否存在来决定进入哪个方法
        if (appraise.getId() != null && appraise.getId().toString().length() > 0) {
            System.out.println(appraise.getId());
            int result = appraiseService.update(appraise);
            int apId = appraise.getId();
            if (!appraise.getScore().equals(appraiseService.queryById(apId).getScore())){
                phyScore(appraise.getPhyId());
            }
            return result;
        } else {
            System.out.println(appraise.getId());
            int result = appraiseService.insert(appraise);
            phyScore(appraise.getPhyId());
            return result;
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/del")
    public int delete(Integer id){
        log.info("当前删除数据的id:{}", id);
        return appraiseService.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public int deleteBatch(@RequestBody List<Integer> ids){
        return appraiseService.deleteByIds(ids);
    }

    /**
     * 导出文件
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询所有数据
        List<Appraise> list = appraiseService.findAll();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("评论信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * 导入文件
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public int  imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Appraise> list = reader.readAll(Appraise.class);
        System.out.println(list);
        return appraiseService.insertBatch(list);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Appraise queryById(Integer id){
        return appraiseService.queryById(id);
    }

}

